import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';

const mapStateToProps = (state) => ({
    list: state.list
});

const mapDispatchToProps = (dispatch) => ({
    deleteData: (index) => {
        dispatch({
            type: 'DELETE_DATA',
            task: index
        });
    },
    add: (task) => {
        dispatch({
            type: 'PUT_DATA',
            task: task
        });
    },
    loadList: async () => {
        const res = await axios({ url: 'http://localhost:8888/' });
        dispatch({
            type: 'LOAD_LIST',
            task: res.data
        });
    }
});

class TodoList extends React.Component {
    state = {
        task: '',
        inputRef: React.createRef()
    }

    handleRemove = (idx) => {
        this.props.deleteData(idx);
    }

    handleChange = (e) => {
        this.setState({
            task: e.target.value
        });
    }

    handleAdd = (e) => {
        if (e.keyCode === 13 && e.target.value) {
            this.props.add(this.state.task);
            this.setState({
                task: ''
            });
        }
    }

    async getList () {
        const { props } = this;
        await props.loadList();
    }

    componentDidMount () {
        this.state.inputRef.current.focus();
        this.getList();
    }

    render () {
        return (
            <div>
                <input type="text" ref={this.state.inputRef} value={this.state.task} onChange={this.handleChange} onKeyUp={this.handleAdd} />
                <ul>
                    {
                        this.props.list.map((item, idx) => (
                            <li key={idx}>
                                {item}
                                <button onClick={() => this.handleRemove(idx)}>x</button>
                            </li>
                        ))
                    }
                </ul>
            </div>
        );
    }
}

const App = connect(
    mapStateToProps,
    mapDispatchToProps
)(TodoList);

export default App;
